package com.yellowpage.bigdata.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.common.Constants;
import com.yellowpage.white.struts.BaseAction;
import com.yellowpage.white.struts.Module;
import com.yellowpage.white.struts.OperationType;
import com.yellowpage.white.util.Util4Java;
import com.yellowpage.bigdata.data.NspOnofflogImeiMonthregionSum;
import com.yellowpage.bigdata.service.NspFatallogRequsetSumService;
import com.yellowpage.bigdata.service.NspOnofflogImeiMonthregionSumService;
import com.yellowpage.ca.data.User;
import com.yellowpage.ca.service.RegionService;

public class NspOnofflogImeiMonthregionSumAction extends BaseAction {

	public String RESULT_QUERY = "query";
	public String RESULT_ADD = "add";
	public String RESULT_EDIT = "edit";

	private Configuration configuration;

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	private List<NspOnofflogImeiMonthregionSum> nspOnofflogImeiMonthregionSumList = new ArrayList<NspOnofflogImeiMonthregionSum>();
	private List<Map> resultList = new ArrayList<Map>();

	private NspOnofflogImeiMonthregionSum nspOnofflogImeiMonthregionSum;
	private NspOnofflogImeiMonthregionSumService nspOnofflogImeiMonthregionSumService;

	private String selectedId;
	private String[] selectedIds;
	private String message;

	private String query_optType;
	private String query_logMonth;
	private String query_createUser;
	private String query_createTime;
	private String query_note;
	private String query_imeiMonthCount;
	private String query_imeiAllCount;
	private String query_imeiNewCount;
	private String query_lastUpdateUser;
	private String query_lastUpdateTime;
	private String query_onofflogImeiMonthregionSumId;
	private String query_tm_start;
	private String query_tm_end;
	private RegionService regionService;
	private String regionName;
	private Map<String, String> regionMap;
	private NspFatallogRequsetSumService nspFatallogRequsetSumService;

	public NspFatallogRequsetSumService getNspFatallogRequsetSumService() {
		return nspFatallogRequsetSumService;
	}

	public void setNspFatallogRequsetSumService(
			NspFatallogRequsetSumService nspFatallogRequsetSumService) {
		this.nspFatallogRequsetSumService = nspFatallogRequsetSumService;
	}

	public Map<String, String> getRegionMap() {
		return regionMap;
	}

	public void setRegionMap(Map<String, String> regionMap) {
		this.regionMap = regionMap;
	}

	public String getRegionName() {
		return regionName;
	}

	public void setRegionName(String regionName) {
		this.regionName = regionName;
	}

	public RegionService getRegionService() {
		return regionService;
	}

	public void setRegionService(RegionService regionService) {
		this.regionService = regionService;
	}

	public String getRegionSql() {
		Map session = ActionContext.getContext().getSession();
		User user = (User) session.get("userObject");
		String function_code = "OMC_CLIENT_LOG_COUNT_MONTH_NSPIMEI";
		String regionsql = regionService.getRegionclauseByUserFunction(
				user.getUserId(), function_code, "REGION_CODE");
		return regionsql;
	}

	public void prepare() {
		super.prepare();

		if (this.selectedId != null && !this.selectedId.equals("")) {
			this.nspOnofflogImeiMonthregionSum = nspOnofflogImeiMonthregionSumService
					.getNspOnofflogImeiMonthregionSum(Long
							.parseLong(selectedId));
		}
	}

	public String queryChannel() {
		initPageRender();
		regionMap = nspFatallogRequsetSumService.getRegionMap(getRegionSql());
		setPageRenderToRequest();
		return "toRegion";
	}

	public String queryByPage() {
		initPageRender();

		Map queryMap = new HashMap();
		if(!regionName.equals("")){
			regionMap = nspFatallogRequsetSumService.getRegionMap(getRegionSql());
			String[] val = regionName.split(";");
			String str = "(";
			for(String ss : val){
				for(String key : regionMap.keySet()){
					if(regionMap.get(key).contains(ss)){
						str += "'" + key + "',";
						break;
					}
				}
			}
			if(str.length()==1){
				str =str.substring(0,1) + "'" + regionName.replaceAll(";", "','") + "')";
			}else{
				str= str.substring(0, str.length() - 1)+")";
			}
			queryMap.put("regionCode", str.substring(str.length()-3, str.length()).equals("'')")?str.substring(0,str.length()-4)+")":str);
		}else{
			queryMap.put("regionCode", regionName);
		}
		queryMap.put("query_tm_start", query_tm_start);
		queryMap.put("query_tm_end", query_tm_end);

		resultList = nspOnofflogImeiMonthregionSumService
				.queryNspOnofflogImeiMonthregionSumByPage(queryMap, pageRender);

		setPageRenderToRequest();

		return RESULT_QUERY;
	}

	public void exportExcel() {
		Map queryMap = new HashMap();
		queryMap.put("query_tm_start", query_tm_start);
		if(!regionName.equals("")){
			regionMap = nspFatallogRequsetSumService.getRegionMap(getRegionSql());
			String[] val = regionName.split(";");
			String str = "(";
			for(String ss : val){
				for(String key : regionMap.keySet()){
					if(regionMap.get(key).contains(ss)){
						str += "'" + key + "',";
						break;
					}
				}
			}
			if(str.length()==1){
				str =str.substring(0,1) + "'" + regionName.replaceAll(";", "','") + "')";
			}else{
				str= str.substring(0, str.length() - 1)+")";
			}
			queryMap.put("regionCode", str.substring(str.length()-3, str.length()).equals("'')")?str.substring(0,str.length()-4)+")":str);
		}else{
			queryMap.put("regionCode", regionName);
		}
		queryMap.put("query_tm_end", query_tm_end);
		resultList = nspOnofflogImeiMonthregionSumService
				.queryNspOnofflogImeiMonthregionSumByPage(queryMap);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/x-download");
		OutputStream outp = null;
		response.addHeader("Content-Disposition", "attachment;filename="
				+ "ImeiMonth.xls");
		try {
			outp = response.getOutputStream();
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("ImeiMonth");
			sheet.autoSizeColumn(1);
			HSSFCellStyle cellStyle = workbook.createCellStyle(); // 单元格格式
			cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 设置右边框
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
			// HSSFRow row = sheet.createRow(0);// 一级标题栏
			// sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
			// row.createCell(0).setCellValue(" ");
			// sheet.addMergedRegion(new CellRangeAddress(0, 0, 4, 5));
			// HSSFCell cell0 = row.createCell(4);
			// cell0.setCellStyle(cellStyle);
			// cell0.setCellValue("运营商");
			// sheet.addMergedRegion(new CellRangeAddress(0, 0, 6, 7));
			// cell0= row.createCell(7);
			// cell0.setCellValue("系统");
			// sheet.addMergedRegion(new CellRangeAddress(0, 0, 8, 9));
			// row.createCell(6).setCellValue(" ");
			HSSFRow row1 = sheet.createRow(0);// 二级标题栏
			String[] title = { "地区代码", "地区名称", "月度 ", "活跃数", "主动活跃数", "被动（来显）",
					"累计用户数 ", "新增" };
			for (int i = 0, len = title.length; i < len; i++) {
				HSSFCell cell = row1.createCell(i);
				cell.setCellValue(title[i]);
			}
			for (int i = 0, len = resultList.size(); i < len; i++) {
				HSSFRow data_row = sheet.createRow(i + 1);
				Map result = resultList.get(i);
				data_row.createCell(0).setCellValue(
						result.get("REGION_CODE") != null ? result.get(
								"REGION_CODE").toString() : "");
				data_row.createCell(1).setCellValue(
						result.get("REGION_NAME") != null ? result.get(
								"REGION_NAME").toString() : "");
				data_row.createCell(2).setCellValue(
						result.get("LOG_MONTH") != null ? result.get(
								"LOG_MONTH").toString() : "");
				data_row.createCell(3).setCellValue(
						result.get("IMEI_MONTH_COUNT") != null ? result.get(
								"IMEI_MONTH_COUNT").toString() : "");
				data_row.createCell(4).setCellValue(
						result.get("ZDNUM") != null ? result.get("ZDNUM")
								.toString() : "");
				data_row.createCell(5).setCellValue(
						result.get("LXNUM") != null ? result.get("LXNUM")
								.toString() : "");
				data_row.createCell(6).setCellValue(
						result.get("IMEI_ALL_COUNT") != null ? result.get(
								"IMEI_ALL_COUNT").toString() : "");
				data_row.createCell(7).setCellValue(
						result.get("IMEI_NEW_COUNT") != null ? result.get(
								"IMEI_NEW_COUNT").toString() : "");
			}
			workbook.write(outp);
			response.flushBuffer();
			outp.flush();
			response.reset();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			this.addActionError("** 生成文件错误 !");
		} finally {
			if (outp != null) {
				try {
					outp.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	public String toAdd() {
		return RESULT_ADD;
	}

	public String save() {

		nspOnofflogImeiMonthregionSumService
				.saveNspOnofflogImeiMonthregionSum(nspOnofflogImeiMonthregionSum);

		message = "新增成功!";
		return RESULT_ADD;
	}

	public void validateSave() {
		if (nspOnofflogImeiMonthregionSum.getRegionCode().length() == 0) {
			this.addActionError("** RegionCode 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getOptType().length() == 0) {
			this.addActionError("** OptType 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getLogMonth().length() == 0) {
			this.addActionError("** LogMonth 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}

		this.setValidatorResult("/bigdata/NspOnofflogImeiMonthregionSumAdd.jsp");
	}

	public String toEdit() {
		Long id = new Long(selectedId);

		nspOnofflogImeiMonthregionSum = nspOnofflogImeiMonthregionSumService
				.getNspOnofflogImeiMonthregionSum(id);

		return RESULT_EDIT;
	}

	public String update() {

		nspOnofflogImeiMonthregionSumService
				.updateNspOnofflogImeiMonthregionSum(nspOnofflogImeiMonthregionSum);

		message = "修改成功!";

		return RESULT_EDIT;
	}

	public void validateUpdate() {
		if (nspOnofflogImeiMonthregionSum.getRegionCode().length() == 0) {
			this.addActionError("** RegionCode 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getOptType().length() == 0) {
			this.addActionError("** OptType 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getLogMonth().length() == 0) {
			this.addActionError("** LogMonth 不能为空 !");
		}
		if (nspOnofflogImeiMonthregionSum.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}
		this.setValidatorResult("/bigdata/NspOnofflogImeiMonthregionSumUpdate.jsp");
	}

	public String delete() {
		List ids = new ArrayList();

		for (String id : selectedIds) {
			ids.add(Long.valueOf(id));
		}

		try {
			this.nspOnofflogImeiMonthregionSumService.delete(ids);
		} catch (Exception e) {
			System.out.println("异常....");
			this.addActionError("可能含有子记录约束冲删除失败 !");
		}

		return queryByPage();
	}

	/**
	 * getters and setters
	 * 
	 * @return
	 */
	public void setNspOnofflogImeiMonthregionSum(
			NspOnofflogImeiMonthregionSum nspOnofflogImeiMonthregionSum) {
		this.nspOnofflogImeiMonthregionSum = nspOnofflogImeiMonthregionSum;
	}

	public NspOnofflogImeiMonthregionSum getNspOnofflogImeiMonthregionSum() {
		return nspOnofflogImeiMonthregionSum;
	}

	public void setNspOnofflogImeiMonthregionSumService(
			NspOnofflogImeiMonthregionSumService nspOnofflogImeiMonthregionSumService) {
		this.nspOnofflogImeiMonthregionSumService = nspOnofflogImeiMonthregionSumService;
	}

	public List<NspOnofflogImeiMonthregionSum> getNspOnofflogImeiMonthregionSumList() {
		return nspOnofflogImeiMonthregionSumList;
	}

	public void setNspOnofflogImeiMonthregionSumList(
			List<NspOnofflogImeiMonthregionSum> nspOnofflogImeiMonthregionSumList) {
		this.nspOnofflogImeiMonthregionSumList = nspOnofflogImeiMonthregionSumList;
	}

	public String getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(String selectedId) {
		this.selectedId = selectedId;
	}

	public String[] getSelectedIds() {
		return selectedIds;
	}

	public void setSelectedIds(String[] selectedIds) {
		this.selectedIds = selectedIds;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<Map> getResultList() {
		return resultList;
	}

	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}


	public String getQuery_optType() {
		return this.query_optType;
	}

	public void setQuery_optType(String optType) {
		this.query_optType = optType;
	}

	public String getQuery_logMonth() {
		return this.query_logMonth;
	}

	public void setQuery_logMonth(String logMonth) {
		this.query_logMonth = logMonth;
	}

	public String getQuery_createUser() {
		return this.query_createUser;
	}

	public void setQuery_createUser(String createUser) {
		this.query_createUser = createUser;
	}

	public String getQuery_createTime() {
		return this.query_createTime;
	}

	public void setQuery_createTime(String createTime) {
		this.query_createTime = createTime;
	}

	public String getQuery_note() {
		return this.query_note;
	}

	public void setQuery_note(String note) {
		this.query_note = note;
	}

	public String getQuery_imeiMonthCount() {
		return this.query_imeiMonthCount;
	}

	public void setQuery_imeiMonthCount(String imeiMonthCount) {
		this.query_imeiMonthCount = imeiMonthCount;
	}

	public String getQuery_imeiAllCount() {
		return this.query_imeiAllCount;
	}

	public void setQuery_imeiAllCount(String imeiAllCount) {
		this.query_imeiAllCount = imeiAllCount;
	}

	public String getQuery_imeiNewCount() {
		return this.query_imeiNewCount;
	}

	public void setQuery_imeiNewCount(String imeiNewCount) {
		this.query_imeiNewCount = imeiNewCount;
	}

	public String getQuery_lastUpdateUser() {
		return this.query_lastUpdateUser;
	}

	public void setQuery_lastUpdateUser(String lastUpdateUser) {
		this.query_lastUpdateUser = lastUpdateUser;
	}

	public String getQuery_lastUpdateTime() {
		return this.query_lastUpdateTime;
	}

	public void setQuery_lastUpdateTime(String lastUpdateTime) {
		this.query_lastUpdateTime = lastUpdateTime;
	}

	public String getQuery_onofflogImeiMonthregionSumId() {
		return this.query_onofflogImeiMonthregionSumId;
	}

	public void setQuery_onofflogImeiMonthregionSumId(
			String onofflogImeiMonthregionSumId) {
		this.query_onofflogImeiMonthregionSumId = onofflogImeiMonthregionSumId;
	}

	public String getQuery_tm_start() {
		return query_tm_start;
	}

	public void setQuery_tm_start(String query_tm_start) {
		this.query_tm_start = query_tm_start;
	}

	public String getQuery_tm_end() {
		return query_tm_end;
	}

	public void setQuery_tm_end(String query_tm_end) {
		this.query_tm_end = query_tm_end;
	}

}
